using System;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using Avalonia;
using AvaloniaUI.Modal.Demo.ViewModels;

namespace AvaloniaUI.Modal.Demo;

public class ViewLocator : IDataTemplate
{
    public Control? Build(object? data)
    {
        if (data is null)
            return null;
        
        // 特殊处理对话框ViewModel
        if (data is MessageDialogViewModel)
        {
            return Application.Current?.FindResource("MessageDialogTemplate") is IDataTemplate template
                ? template.Build(data)
                : new TextBlock { Text = "MessageDialogTemplate not found" };
        }
        
        if (data is InputDialogViewModel)
        {
            return Application.Current?.FindResource("InputDialogTemplate") is IDataTemplate template
                ? template.Build(data)
                : new TextBlock { Text = "InputDialogTemplate not found" };
        }
        
        // 默认处理
        var name = data.GetType().FullName!.Replace("ViewModel", "View", StringComparison.Ordinal);
        var type = Type.GetType(name);

        if (type != null)
        {
            var control = (Control)Activator.CreateInstance(type)!;
            control.DataContext = data;
            return control;
        }
        
        return new TextBlock { Text = "Not Found: " + name };
    }

    public bool Match(object? data)
    {
        return data is ViewModelBase;
    }
}
